package com.lebang.controller.api.bus;

import com.lebang.aop.Sessionid;
import com.lebang.common.Require;
import com.lebang.common.validcode.RedisLogin;
import com.lebang.common.validcode.ValidCodeStatus;
import com.lebang.common.validcode.ValidCodeUtil;
import com.lebang.component.RedisClient;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.model.ValidCodeRecord;
import com.lebang.model.WeixinInfo;
import com.lebang.model.enums.Gender;
import com.lebang.service.buss.MemberService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import static com.lebang.common.validcode.RedisLock.LOCKPHONECODE;

@Api(tags = "公交微信登录")
@RestController
@RequestMapping("/bus/login")
public class BusLoginApi {
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ValidCodeUtil validCodeUtil;
    public static final String BUS_MEMBER_KEY="BUS_MEMBER_KEY";

    /**
     * 公交用户微信登录
     *
     * @return
     */
    @Sessionid
    @PostMapping("/register")
    public JsonData busRegister(HttpServletRequest request, @RequestParam(value = "openid") String openid, String nickname, Integer sex, String headimgurl,
                                @RequestParam(value = "params", required = false) String params, String city) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        if (TextUtil.isEmpty(openid)) {
            return Callback.fail("201", "登录失败!");
        }
        LbbMember member = memberService.selectByOpenId(openid);
        if (member != null) {
            return Callback.success("200", "登录成功", member);
        } else {
            try {
                WeixinInfo weixinInfo = new WeixinInfo();
                weixinInfo.setOpenId(openid);
                weixinInfo.setStatus(1);
                weixinInfo.setNickName(nickname);
                weixinInfo.setAvatar(headimgurl);
                if (sex != null && sex == 1) {
                    weixinInfo.setGender(Gender.Male.name());
                } else {
                    weixinInfo.setGender(Gender.Female.name());
                }
                LbbMember memberInfo = memberService.createMemberInfo(request, requestHeaders, weixinInfo, city);
                return Callback.success("200", "登录成功", memberInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return Callback.success("201", "登录失败");
        }
    }

    /**
     * 公交用户获取验证码
     */
    @Sessionid
    @PostMapping("/code")
    public JsonData busCode(HttpServletRequest request, @RequestParam(value = "phone") String phone) {
        try {
            RequestHeaders requestHeaders = new RequestHeaders(request);
            if (!TextUtil.isMobile(phone)) {
                return Callback.fail("invalid_phone", "请输入正确的手机号！");
            }
            //加锁防止重复发
            String uuid = UUIDUtil.M();
            boolean a = redisClient.tryGetDistributedLock(LOCKPHONECODE.getName() + phone, uuid, 3000);
            if (a) {
                LbbMember member = memberService.selectByMemberId(requestHeaders.getUserid());
                if (member == null){
                    return Callback.fail("fail", "用户不存在");
                }
                if (!TextUtil.isEmpty(member.getPhone())) {
                    return Callback.fail("fail", "一个账号只能绑定一个手机号");
                }
                ValidCodeStatus validCode = validCodeUtil.getValidCode(phone, new ValidCodeRecord(request));
                if (validCode.isStatus()) {
                    //验证码存入redis中
                    redisClient.setex(RedisLogin.PHONE_NEW_LOGIN_CODE.getName() + phone, 300, validCode.getCode());

                    return Callback.success("success", "发送成功", "");
                } else {
                    return Callback.fail("fail", "发送失败" + validCode.getMsg());
                }
            } else {
                return Callback.fail("fail", "请勿重复操作哦");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Callback.fail("error", e.getMessage());
        }
    }

    /**
     * 公交用户绑定手机号
     */
    @Sessionid
    @PostMapping("/bind")
    public JsonData busBind(HttpServletRequest request, @RequestParam(value = "phone") String phone, @RequestParam(value = "code") String code) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        LbbMember lbbMember = memberService.selectByPhone(phone);
        if (lbbMember != null) {
            return Callback.fail("fail", "该手机号已绑定过账号");
        }
        // 校验验证码
        if (!validCodeUtil.checkCode(phone, RedisLogin.PHONE_NEW_LOGIN_CODE, code)) {
            return Callback.fail("invalid_code", "验证码错误！");
        }
        //验证成功删除验证码
        validCodeUtil.cleanCode(phone, RedisLogin.PHONE_NEW_LOGIN_CODE, code);
        int i = memberService.updateByMemberId(requestHeaders.getUserid(), phone);
        if (i > 0) {
            return Callback.success("success", "绑定成功");
        } else {
            return Callback.fail("fail", "绑定失败");
        }
    }

    /**
     * 退出登录请求接口
     *
     * @param request
     * @return
     */
    @Require
    @Sessionid
    @PostMapping("/out")
    public JsonData out(HttpServletRequest request) {
//        RequestHeaders requestHeaders = new RequestHeaders(request);
//        LbbMember member = memberService.selectMemberById(requestHeaders.getUserid());
//        memberService.insertLoginRecord(member.getPhone(),requestHeaders);
        return Callback.success("200", "退出登录成功");
    }

    /**
     * 检测登录用户是否是新用户
     */
    @Require
    @Sessionid
    @PostMapping("/isnew")
    public JsonData isNew(HttpServletRequest request) {
        RequestHeaders requestHeaders = new RequestHeaders(request);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        int todayTime = Integer.parseInt(LocalDate.now().format(df));
        String value;
        if (redisClient.hexists(BUS_MEMBER_KEY+ todayTime, requestHeaders.getUserid() + ":" + requestHeaders.getImei())) {
            //缓存
            value=redisClient.hget(BUS_MEMBER_KEY+todayTime, requestHeaders.getUserid() + ":" + requestHeaders.getImei());
        }else {
            //查库
            LbbMember member = memberService.getMemberByMemberId(requestHeaders.getUserid());
            LocalDate localDate = member.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            if (localDate.isEqual(LocalDate.now())){
                value="1";
            }else {
                value="0";
            }
            //写缓存
            redisClient.hset(BUS_MEMBER_KEY+ todayTime,requestHeaders.getUserid() + ":" + requestHeaders.getImei(),value);
        }
        return Callback.fail("200", "查询成功",value);
    }
}
